<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="主题" prop="ruleTheme">
        <el-input
          v-model="queryParams.ruleTheme"
          placeholder="请输入主题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
        <!-- v-hasPermi="['task:rules:add']"-->
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="rulesList" @selection-change="handleSelectionChange">
      <el-table-column label="主题" align="center" prop="ruleTheme" />
      <el-table-column label="添加时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="添加人" align="center" prop="createUserName" />
      <el-table-column label="是否启用" align="center" prop="isUse" :formatter="statusFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEnable(scope.row)"
          >{{scope.row.isUse == 0?'禁用':"启用"}}</el-button>
          <!--v-hasPermi="['task:rules:enable']"-->
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改任务企业抽取规则对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="950px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="220px">
        <el-form-item label="1、任务对象抽取主题" prop="ruleTheme">
          <el-input v-model="form.ruleTheme" placeholder="请输入主题" />
        </el-form-item>
        <el-row :gutter="30">
          <el-col :span="15">
            <el-form-item label="2、任务对象抽取数量" prop="extractionNum">
              <el-input
                v-model.number="form.extractionNum"
                type="number"
                placeholder="请输入抽取数量"
                @blur="validateMax(form.extractionNum)"
              />
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="所有对象数:">{{allObjectNum}}</el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="3、任务对象随机参考表" label-width="235px"></el-form-item>
        <el-form-item label="3.1、投诉举报企业列表" prop="complaintUse" label-width="285px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleSelectComplaint(scope.row)"
              :disabled="form.complaintUse==1?true:false"
            >选择企业</el-button>

            <el-select v-model="form.complaintUse" placeholder="请选择启用或禁用">
              <el-option
                v-for="dict in taskTemplateUseStatus"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
            <span class="selectComplainNumber" v-if="id1.length&&id1.length!=0">已选择企业数量：{{id1.length}}</span>
          </template>
        </el-form-item>
        <el-form-item label="3.2、失信行为企业列表" prop="dishonestyUse" label-width="285px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleSelectDishonesty(scope.row)"
              :disabled="form.dishonestyUse==1?true:false"
            >选择企业</el-button>

            <el-select v-model="form.dishonestyUse" placeholder="请选择启用或禁用">
              <el-option
                v-for="dict in taskTemplateUseStatus"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
             <span class="selectComplainNumber" v-if="id2.length&&id2.length!=0">已选择企业数量：{{id2.length}}</span>
          </template>
        </el-form-item>
        <el-form-item label="3.3、严重违法违规企业列表" prop="illegalUse" label-width="285px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleSelectIllegal(scope.row)"
              :disabled="form.illegalUse==1?true:false"
            >选择企业</el-button>

            <el-select v-model="form.illegalUse" placeholder="请选择启用或禁用">
              <el-option
                v-for="dict in taskTemplateUseStatus"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
             <span class="selectComplainNumber" v-if="id3.length&&id3.length!=0">已选择企业数量：{{id3.length}}</span>
          </template>
        </el-form-item>
        <el-form-item label="3.4、必抽企业列表" prop="mustCheckUse" label-width="285px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleSelectMustCheck"
              :disabled="form.mustCheckUse==1?true:false"
            >选择企业</el-button>

            <el-select v-model="form.mustCheckUse" placeholder="请选择启用或禁用">
              <el-option
                v-for="dict in taskTemplateUseStatus"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
             <span class="selectComplainNumber" v-if="id4.length&&id4.length!=0">已选择企业数量：{{id4.length}}</span>
          </template>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="submitForm">确 定</el-button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <el-button @click="cancel">重 置</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="detailContent.title"
      :visible.sync="detailContent.open"
      width="850px"
      :before-close="handleDialogClose"
      append-to-body
    >
      <elTransFer :dataList="detailContent.detailList" :selectType="selectType" :showsName="id" v-on:BindhandleChange="BindhandleChange"></elTransFer>
      <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitDetailForm">确 定</el-button>
          <el-button @click="detailcancel">取 消</el-button>
     </div>
      <!-- <el-row :gutter="30">
        <el-col :span="10">
          <div>
            <el-table
              v-loading="detailContent.loading"
              ref="multipleTable"
              :data="detailContent.detailList"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="企业名称" align="center" prop="stationName" />
            </el-table>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitDetailForm">确 定</el-button>
              <el-button @click="detailcancel">取 消</el-button>
            </div>
          </div>
        </el-col>
         <el-col :span="10">
          <div>
            <el-table v-loading="detailContent.loading" :data="detailContent.trueDataList">
              <el-table-column
                label="选中的企业名称"
                align="center"
                prop="showedId"
                :formatter="stationNameFormat"
              />
            </el-table>
          </div>
        </el-col>
      </el-row> -->
    </el-dialog>
  </div>
</template>

<script>
import {
  listRules,
  getRules,
  delRules,
  addRules,
  updateRules,
  exportRules,
  receiveObjectNum,
  changeUseStatus,
  getStationList,
  getCheckedList,
} from "@/api/task/rules";
import elTransFer from '@/components/el-transfer'
export default {
  name: "Rules",
  data() {
    return {
      allObjectNum: 0,
      id:[],
      id1: [],
      id2:[],
      id3:[],
      id4:[],
      selectType:1,
      //1-投诉举报企业列表;2-失信行为企业列表;3-严重违法违规企业列表;4-必抽企业列表
      detailContent: {
        open: false,
        title: "",
        dialogType: 0,
        loading: true,
        tatal: 0,
        //展示的ids
        detailList: [],
        showIdsList: [],
        trueDataList: [],
        fromDBcheckedList: [],

        //投诉举报企业的选中ids
        complaintIds: [],
        //失信行为企业的选中ids
        dishonestyIds: [],

        //严重违法违规企业的选中ids
        illegalIds: [],

        //必抽企业的选中ids
        mustCheckIds: [],
        //点击修改时的ruleId
        ruleId: "",
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      stationNames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 任务企业抽取规则表格数据
      rulesList: [],
      // 启用状态字典
      taskTemplateUseStatus: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ruleTheme: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        ruleTheme: [
          { required: true, message: "主题不能为空", trigger: "blur" },
        ],
        extractionNum: [
          { required: true, message: "抽取数量不能为空", trigger: "blur" },
        ],
      },
    };
  },
  components:{elTransFer},
  created() {
    this.getList();
    this.getDicts("task_template_use_status").then((response) => {
      this.taskTemplateUseStatus = response.data;
    });
    this.getAllObjectNum();
  },
  methods: {
    validateMax(inputNum) {
      if (inputNum > this.allObjectNum) {
        this.msgError("请输入不大于所有对象数的值：" + this.allObjectNum);
      }
    },
    addIdsDataToForm() {
      // this.form.complaintIds = this.detailContent.complaintIds;
      // this.form.dishonestyIds = this.detailContent.dishonestyIds;
      // this.form.illegalIds = this.detailContent.illegalIds;
      // this.form.mustCheckIds = this.detailContent.mustCheckIds;
        this.form.complaintIds = this.id1;
      this.form.dishonestyIds = this.id2;
      this.form.illegalIds = this.id3;
      this.form.mustCheckIds = this.id4;
    },
    /** 查询任务企业抽取规则列表 */
    getList() {
      this.loading = true;
      listRules(this.queryParams).then((response) => {
        this.rulesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //获取所有对象数量
    getAllObjectNum() {
      this.loading = true;
      receiveObjectNum().then((response) => {
        this.allObjectNum = response.data;
        this.loading = false;
      });
    },

    /** 查询场站信息列表 */
    async receiveStationList() {
      this.detailContent.loading = true;
      await getStationList().then((response) => {
        this.detailContent.detailList = response.rows;
        this.detailContent.loading = false;
      });
    },
    async receiveCheckedList(type, id) {
      await getCheckedList(type, id).then((response) => {
        this.detailContent.loading = false;
        if (type == 1) {
          this.id1=[]
          this.detailContent.fromDBcheckedList = response.rows;
         response.rows.forEach((data) => {
            this.id1=[...this.id1,data.stationId]
          });
        }
        if (type == 2) {
          this.id2=[]
          this.detailContent.fromDBcheckedList = response.rows;
          response.rows.forEach((data) => {
            this.id2=[...this.id2,data.stationId]
          });
        }
        if (type == 3) {
          this.id3=[]
          this.detailContent.fromDBcheckedList = response.rows;
          response.rows.forEach((data) => {
            this.id3=[...this.id3,data.stationId]
          });
        }
        if (type == 4) {
          this.id4=[]
          this.detailContent.fromDBcheckedList = response.rows;
          response.rows.forEach((data) => {
            this.id4=[...this.id4,data.stationId]
          });
        }
        this.detailContent.total = response.total;
        this.detailContent.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.taskTemplateUseStatus, row.isUse);
    },
    //企业翻译
    stationNameFormat(row, column) {
      return this.selectStationNameFormat(
        this.detailContent.detailList,
        row.showedId
      );
    },
    selectStationNameFormat(datas, value) {
      var actions = [];
      Object.keys(datas).some((key) => {
        if (datas[key].id == "" + value) {
          actions.push(datas[key].stationName);
          return true;
        }
      });
      return actions.join("");
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        ruleTheme: undefined,
        extractionNum: undefined,
        complaintUse: undefined,
        dishonestyUse: undefined,
        illegalUse: undefined,
        mustCheckUse: undefined,
        isUse: undefined,
        deptId: undefined,
        delFlag: undefined,
        createTime: undefined,
        createId: undefined,
        updateTime: undefined,
        updateId: undefined,
        remark: undefined,
      };
      this.resetForm("form");
    },
    resetDetailContent() {
      this.detailContent = {
        open: false,
        title: "",
        dialogType: 0,
        loading: false,
        tatal: 0,
        //展示的ids
        detailList: [],
        showIdsList: [],
        trueDataList: [],
        fromDBcheckedList: [],

        //投诉举报企业的选中ids
        complaintIds: [],
        //失信行为企业的选中ids
        dishonestyIds: [],

        //严重违法违规企业的选中ids
        illegalIds: [],

        //必抽企业的选中ids
        mustCheckIds: [],
        //点击修改时的ruleId
        ruleId: "",
      };
      this.resetForm("detailContent");
    },
    resetDetailContentEdit() {
      this.detailContent = {
        open: false,
        title: "",
        dialogType: 0,
        loading: false,
        tatal: 0,
        //展示的ids
        detailList: [],
        showIdsList: [],
        trueDataList: [],
        fromDBcheckedList: [],

        //投诉举报企业的选中ids
        complaintIds: [],
        //失信行为企业的选中ids
        dishonestyIds: [],

        //严重违法违规企业的选中ids
        illegalIds: [],

        //必抽企业的选中ids
        mustCheckIds: [],
        //点击修改时的ruleId
        ruleId: "",
      };
      this.resetForm("detailContent");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {

      this.reset();
      this.resetDetailContent();
      this.open = true;
      this.title = "添加任务企业抽取规则";
      this.id1=[],
      this.id2=[],
      this.id3=[],
      this.id4=[]
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.resetDetailContentEdit();
      const id = row.id;
      this.detailContent.ruleId = id;
      getRules(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "查看任务企业抽取规则";
        this.receiveCheckedList(1, this.form.id);
        this.receiveCheckedList(2, this.form.id);
        this.receiveCheckedList(3, this.form.id);
        this.receiveCheckedList(4, this.form.id);
      });
    },
    detailcancel() {
      if(this.detailContent.ruleId==''){
        if(this.selectType==1){
        this.id1=[]
      }else if(this.selectType==2){
        this.id2=[]
      }else if(this.selectType==3){
       this.id3=[]
      }else{
         this.id4=[]
      }
      }
    //  this.$refs.multipleTable.clearSelection();
      this.detailContent.open = false;
    },
    handleDialogClose() {
      // this.$refs.multipleTable.clearSelection();
      this.detailContent.open = false;
    },
    addToTrueDataList() {
      this.detailContent.trueDataList = [];
      if (this.detailContent.dialogType == 1) {
        this.detailContent.showIdsList = this.detailContent.complaintIds;
      }
      if (this.detailContent.dialogType == 2) {
        this.detailContent.showIdsList = this.detailContent.dishonestyIds;
      }
      if (this.detailContent.dialogType == 3) {
        this.detailContent.showIdsList = this.detailContent.illegalIds;
      }
      if (this.detailContent.dialogType == 4) {
        this.detailContent.showIdsList = this.detailContent.mustCheckIds;
      }
      if (this.detailContent.showIdsList.length != 0) {
        this.detailContent.showIdsList.forEach((id) => {
          const showedIdForm = {};
          showedIdForm.showedId = id;
          this.detailContent.trueDataList.push(showedIdForm);
        });
      }
    },

    /** 启用禁用按钮操作*/
    handleEnable(row) {
      //只能一个个禁用，如要更改 添加       const ids = row.id || this.ids;
      const id = row.id;
      const ruleTheme = row.ruleTheme;
      const useStatus = row.isUse;
      this.$confirm(
        '是否确认更改主题为"' + ruleTheme + '"的启用状态?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return changeUseStatus(id, useStatus);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("更改成功");
        })
        .catch(function () {});
    },
    async handleSelectComplaint(row) {


      const type = 1;
      const ruleId = this.detailContent.ruleId;
      this.detailContent.open = true;

      if (this.detailContent.detailList.length == 0) {
        await this.receiveStationList();
      }
      if (
        ruleId != null &&
        typeof ruleId != "undefined" &&
        ruleId != "" &&
        this.id1.length == 0
      ) {
        await this.receiveCheckedList(type, ruleId);
      }
      this.selectType=1;
      this.id=this.id1
      this.detailContent.dialogType = type;

    },
    async handleSelectDishonesty(row) {
      const type = 2;
      this.detailContent.open = true;
      const ruleId = this.detailContent.ruleId;
      if (
        ruleId != null &&
        typeof ruleId != "undefined" &&
        ruleId != "" &&
        this.id2.length == 0
      ) {
        await this.receiveCheckedList(type, ruleId);
      }
      if (this.detailContent.detailList.length == 0) {
        await this.receiveStationList();
      }
      this.selectType=2
      this.id=this.id2
      this.detailContent.dialogType = type;

    },
    async handleSelectIllegal(row) {
      const type = 3;
      this.detailContent.open = true;
      const ruleId = this.detailContent.ruleId;
      if (
        ruleId != null &&
        typeof ruleId != "undefined" &&
        ruleId != "" &&
        this.id3.length == 0
      ) {
        await this.receiveCheckedList(type, ruleId);
      }
      if (this.detailContent.detailList.length == 0) {
        await this.receiveStationList();
      }
         this.selectType=3
      this.id=this.id3
       this.detailContent.dialogType = type;
    },
    async handleSelectMustCheck(row) {
      const type = 4;
      this.detailContent.open = true;
      const ruleId = this.detailContent.ruleId;
      if (
        ruleId != null &&
        typeof ruleId != "undefined" &&
        ruleId != "" &&
        this.id4.length == 0
      ) {
        await this.receiveCheckedList(type, ruleId);
      }
      if (this.detailContent.detailList.length == 0) {
        await this.receiveStationList();
      }
          this.selectType=4
      this.id=this.id4
      this.detailContent.dialogType = type;


    },
    trueCheckNum() {
      var checkIds = [];
      if (this.form.complaintUse == 0) {
        checkIds = checkIds.concat(this.form.complaintIds);
      }
      if (this.form.dishonestyUse == 0) {
        checkIds = checkIds.concat(this.form.dishonestyIds);
      }
      if (this.form.illegalUse == 0) {
        checkIds = checkIds.concat(this.form.illegalIds);
      }
      if (this.form.mustCheckUse == 0) {
        checkIds = checkIds.concat(this.form.mustCheckIds);
      }
      checkIds = this.unique(checkIds);
      return checkIds.length;
    },
    unique(ids) {
      return Array.from(new Set(ids));
    },
    /** 提交按钮 */
    submitForm: function () {
      if (this.form.extractionNum > this.allObjectNum) {
        this.msgError("抽查数请输入不大于所有对象数的值：" + this.allObjectNum);
        return;
      }
      this.addIdsDataToForm();
      if (this.trueCheckNum() > this.form.extractionNum) {
        this.msgError(
          "必选项应该不大于抽查数的值：" + this.form.extractionNum
        );
        return;
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            updateRules(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addRules(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    submitDetailForm() {

      // if (this.detailContent.dialogType == 1) {
      //   this.detailContent.complaintIds = this.ids;
      // }
      // if (this.detailContent.dialogType == 2) {
      //   this.detailContent.dishonestyIds = this.ids;
      // }
      // if (this.detailContent.dialogType == 3) {
      //   this.detailContent.illegalIds = this.ids;
      // }
      // if (this.detailContent.dialogType == 4) {
      //   this.detailContent.mustCheckIds = this.ids;
      // }
      // this.$refs.multipleTable.clearSelection();
      this.detailContent.open = false;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        '是否确认删除任务企业抽取规则编号为"' + ids + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delRules(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有任务企业抽取规则数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportRules(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        })
        .catch(function () {});
    },
    BindhandleChange(value) {
      if(value.selectType==1){
        this.id1=value.value
      }else if(value.selectType==2){
         this.id2=value.value
      }else if(value.selectType==3){
         this.id3=value.value
      }
      else if(value.selectType==4){
         this.id4=value.value
      }
    },
  },
};
</script>
<style scoped>
 .selectComplainNumber{
   color:red;
   font-size:12px;
 }
 .dialog-footer{
   text-align:center;
 }
 .el-transfer{
   display:flex;
   width:80%;
   justify-content: space-around;
   align-content: center;
   margin:0 auto;
 }
 .el-transfer-panel{
   width:300px;
   height:500px;
 }
 .el-transfer__buttons{
    vertical-align:middle;
 }
</style>
